package de.baumann.browser.utils;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.media.SoundPool;
import android.os.Build;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import de.baumann.browser.R;
import de.baumann.browser.api.net.vo.Improve;
import de.baumann.browser.api.net.vo.MineService;

import static de.baumann.browser.utils.Constants.NOT_LICENCE;

/**
 * @author:
 * @date:2019/1/7 10:14
 * @discription: view 工具类
 */
public class ViewUtil {

    public static View emptyView(Context mContext) {
        return LayoutInflater.from(mContext).inflate(R.layout.empty_view, null, false);
    }

    public static Point getScreenSize(Context context) {
        WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        assert manager != null;
        Display display = manager.getDefaultDisplay();
        Point realSize = new Point();
        display.getRealSize(realSize);
        return realSize;
    }

    public static boolean isInstalledQQ(Context context) {
        final PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if ("com.tencent.qqlite".equalsIgnoreCase(pn) || "com.tencent.mobileqq".equalsIgnoreCase(pn)) {
                    return true;
                }
            }
        }
        return false;
    }


    public static boolean isInstalledWX(Context context) {
        final PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if ("com.tencent.mm".equals(pn)) {
                    return true;
                }
            }
        }
        return false;
    }

    @SuppressLint("SetJavaScriptEnabled")
    public static void configWebView(WebView webView) {
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);

        webSettings.setSupportZoom(true);
        webSettings.setBuiltInZoomControls(true);
        webSettings.setDisplayZoomControls(false);

        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webSettings.setAllowFileAccess(true);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setLoadsImagesAutomatically(true);
        webSettings.setDefaultTextEncodingName("utf-8");

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        webView.setWebChromeClient(new WebChromeClient());
    }


    public static int getWindowWidth(Context context) {
        return context.getResources().getDisplayMetrics().widthPixels;
    }

    public static void animateShowFromAlpha(final View view, final boolean show,
                                            boolean animate, int duration, int startDelay, final Runnable onCompleteRunnable) {
        if (animate) {
            float startAlpha = show ? 0.0f : 1.0f;
            float finalAlpha = show ? 1.0f : 0.0f;
            ObjectAnimator animator = ObjectAnimator.ofFloat(view, "alpha", startAlpha, finalAlpha);
            animator.setDuration(duration);
            animator.setStartDelay(startDelay);
            animator.addListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationCancel(Animator animation) {
                    if (onCompleteRunnable != null) {
                        onCompleteRunnable.run();
                    }
                }

                @Override
                public void onAnimationEnd(Animator animation) {
                    if (onCompleteRunnable != null) {
                        onCompleteRunnable.run();
                    }
                }
            });
            animator.start();
        } else {
            view.setVisibility(show ? View.VISIBLE : View.GONE);
            view.setAlpha(show ? 1.0f : 0.0f);
        }
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    private static float scale;

    public static int dip2px(Context context, float dpValue) {
        if (scale == 0) {
            scale = context.getResources().getDisplayMetrics().density;
        }
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        if (scale == 0) {
            scale = context.getResources().getDisplayMetrics().density;
        }
        return (int) (pxValue / scale + 0.5f);
    }

    public static int px2sp(Context context, float pxValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (pxValue / fontScale + 0.5f);
    }

    private static SoundPool soundPool;

    private static void createSoundPool() {
        soundPool = new SoundPool.Builder()
                .setMaxStreams(10)
                .build();
    }

    public static void soundPlay(Context context) {
        playAudio(context,R.raw.sound);
    }

    public static void scanPlay(Context context){
        playAudio(context,R.raw.scan);
    }

    private static void playAudio(Context context,int audioId){
        if (soundPool == null) {
            createSoundPool();
        }
        int rourceId = soundPool.load(context, audioId, 1);
        soundPool.setOnLoadCompleteListener((soundPool, sampleId, status) ->
                soundPool.play(rourceId, 0.5f, 0.5f, 1, 0, 1));
    }


    public static List<MineService> getMineOptions() {
        MineService upgradeMode = new MineService(R.drawable.me_icon_invite, R.string.invite_friends, 0);

        MineService upgradeMode1 = new MineService(R.drawable.me_icon_node, R.string.super_node,
                1);

        MineService upgradeMode2 = new MineService(R.drawable.me_icon_licence, R.string.licence_manager,
                2);

        MineService upgradeMode3 = new MineService(R.drawable.me_icon_pool, R.string.pool,
                3);

        MineService upgradeMode4 = new MineService(R.drawable.me_icon_plan, R.string.plane,
                4);

        MineService upgradeMode5 = new MineService(R.drawable.duobao, R.string.duobao,
                5);

        MineService upgradeMode6 = new MineService(R.drawable.me_icon_service, R.string.me_service,
                6);

        List<MineService> upgradeModes = new ArrayList<>();

//        upgradeModes.add(upgradeMode);
//        upgradeModes.add(upgradeMode1);
        upgradeModes.add(upgradeMode2);
//        if (ActiveUtil.INSTANCE.poolIsOpen()) {
//            upgradeModes.add(upgradeMode3);
//        }
        upgradeModes.add(upgradeMode4);

//        upgradeModes.add(upgradeMode5);
//        upgradeModes.add(upgradeMode6);
        return upgradeModes;
    }

    public static List<Improve> getImproveOptions(Context context) {

        List<Improve> improves = new ArrayList<>();

        Improve improve1 = new Improve(R.drawable.explore_btn_buy, context.getString(R.string.buy_hash), context.getString(R.string.im_01));
        Improve improve2 = new Improve(R.drawable.explore_btn_redpacket, context.getString(R.string.redpack), context.getString(R.string.im_06));
        Improve improve3 = new Improve(R.drawable.explore_btn_node, context.getString(R.string.super_node), context.getString(R.string.im_07));
        Improve improve4 = new Improve(R.drawable.explore_btn_card, context.getString(R.string.black_card_user), context.getString(R.string.im_08));
        Improve improve6 = new Improve(R.drawable.explore_btn_invite, context.getString(R.string.invite_friends), context.getString(R.string.im_02));

        if (UserDataKt.getLicenceStatus() != NOT_LICENCE) {
            improves.add(improve1);
        }

        improves.add(improve2);
        improves.add(improve3);
        improves.add(improve4);
//        improves.add(improve6);

        return improves;
    }

    public static List<Improve> getExploreOptions(Context context) {

        List<Improve> improves = new ArrayList<>();

        Improve improve1 = new Improve(R.drawable.explore_btn_buy, context.getString(R.string.buy_hash), context.getString(R.string.im_01));
//        Improve improve2 = new Improve(R.drawable.explore_btn_redpacket, context.getString(R.string.redpack), context.getString(R.string.im_06));
        Improve improve3 = new Improve(R.drawable.explore_btn_node, context.getString(R.string.super_node), context.getString(R.string.im_07));
//        Improve improve4 = new Improve(R.drawable.explore_btn_card, context.getString(R.string.black_card_user), context.getString(R.string.im_08));
//        Improve improve6 = new Improve(R.drawable.explore_btn_invite, context.getString(R.string.invite_friends), context.getString(R.string.im_02));
        improves.add(improve1);
//        improves.add(improve2);
        improves.add(improve3);
//        improves.add(improve4);
//        improves.add(improve6);

        return improves;
    }

    public static boolean isDoubleClick(View v) {
        Object tag = v.getTag(v.getId());
        long beforeTimemiles = tag != null ? (long) tag : 0;
        long timeInMillis = Calendar.getInstance().getTimeInMillis();
        v.setTag(v.getId(), timeInMillis);
        return timeInMillis - beforeTimemiles < 1000;
    }


    public static Drawable drawText2Bitmap(String text, int imgResourceId, Context mContext) {
        try {
            Resources resources = mContext.getResources();
            float scale = resources.getDisplayMetrics().density;
            Bitmap bitmap = BitmapFactory.decodeResource(resources, imgResourceId);

            android.graphics.Bitmap.Config bitmapConfig = bitmap.getConfig();

            if (bitmapConfig == null) {
                bitmapConfig = android.graphics.Bitmap.Config.ARGB_8888;
            }

            bitmap = bitmap.copy(bitmapConfig, true);

            Canvas canvas = new Canvas(bitmap);
            Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
            paint.setColor(Color.rgb(110, 110, 110));
            paint.setTextSize((int) (14 * scale));
            paint.setShadowLayer(1f, 0f, 1f, Color.DKGRAY);

            // draw text to the Canvas center
            Rect bounds = new Rect();
            paint.getTextBounds(text, 0, text.length(), bounds);
            int x = (bitmap.getWidth() - bounds.width()) / 2;
            int y = (bitmap.getHeight() + bounds.height()) / 2;

            canvas.drawText(text, x, y, paint);
            return new BitmapDrawable(resources, bitmap);
        } catch (Exception e) {
            return null;
        }
    }

    public static int getStatusBarHeight(Context context) {
        Resources resources = context.getResources();
        int resourceId = resources.getIdentifier("status_bar_height", "dimen", "android");
        int height = resources.getDimensionPixelSize(resourceId);
        return height;
    }

    public static float sp2px(Context context, float spValue) {
        float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (spValue * fontScale + 0.5f);
    }
}
